package com.whosly.study.webflux.config;

import com.whosly.study.webflux.service.CreateGrpcServer;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import java.io.IOException;

@Configuration
@Slf4j
public class GRPCConfiguration implements InitializingBean, ApplicationRunner {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void afterPropertiesSet() throws Exception {
        //.
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Integer port = 8081;
        Assert.notNull(port, "Illegal grpc server port.");

        try {
            BindableService createGrpcServer = buildCreateGrpcServer();

            Server server = ServerBuilder.forPort(port)
                    .addService(createGrpcServer)
                    .build();

            // Start the server
            server.start();

            logger.info("Run GRpc Server success with port: {} .", port);

//            server.awaitTermination();
        } catch (Exception e) {
            logger.error("GRpc Server exception: " + e.getMessage(), e);
        }
    }

    private BindableService buildCreateGrpcServer() {
        return new CreateGrpcServer();
    }

}
